<template>
  <div class="UploadFile-container">
    <el-upload :action="define.comUploadUrl + '/' + modular + '/' + type" :headers="uploadHeaders"
      :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :on-success="handleSuccess"
      :file-list="fileList" :accept="accept">
      <el-button size="small" icon="el-icon-upload">选择文件</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadFileSingle',
  props: {
    value: {
      type: Array,
      default: () => ([])
    },
    modular: {
      type: String,
      default: 'system'
    },
    type: {
      type: String,
      default: 'annex'
    },
    accept: {
      type: String,
      default: '*'
    }
  },
  data() {
    return {
      fileList: [],
      uploadHeaders: { Authorization: this.$store.getters.token }
    }
  },
  watch: {
    value(val) {
      this.fileList = val
    }
  },
  methods: {
    handlePreview(file) { },
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.$emit('input', fileList)
    },
    handleSuccess(res, file, fileList) {
      // if (res.code == 200) {
      //   // this.fileList.push() = fileList
      //   const list = this.fileList
      //   list.push(file.response.data)
      //   this.$emit('input', list)
      // } else {
      //   this.fileList = fileList.filter((o) => o.uid != file.uid)
      //   this.$message({ message: res.msg, type: 'error', duration: 1500 })
      // }

      if (res.code == 200) {
        const list = [...this.fileList];
        // 确保文件对象包含 name 属性
        const uploadedFile = {
          ...file.response.data,
          name: file.name // 保留原始文件名
        };
        list.push(uploadedFile);
        this.$emit('input', list);
      } else {
        this.fileList = fileList.filter((o) => o.uid != file.uid);
        this.$message({ message: res.msg, type: 'error', duration: 1500 });
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).catch(() => { })
    }
  }
}
</script>
